<template>
  <default-home-card icon="Profile" title="销售统计" :tabs="tabs" @tabChange="onTabChange">
    <div class="echarts-box">
      <div class="category-main" id="category-main"></div>
    </div>
  </default-home-card>
</template>

<script setup lang="ts">
import DefaultHomeCard from '@/views/system/home/components/default-home-card.vue'
import * as echarts from 'echarts'
import { onMounted, ref, nextTick } from 'vue'
import { homeApi } from '@/api/system/home-api'

const time_type = ref(1)
const tabs = ref([
  { key: '1', title: '今天' },
  { key: '2', title: '本周' },
  { key: '3', title: '本月' }
])

function onTabChange(key: string) {
  time_type.value = key
  init()
}

onMounted(() => {
  init()
})

async function init() {
  let option = {
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    legend: {
      data: []
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    series: []
  }

  const data = await homeApi.brandSalesStatistics({ time_type: time_type.value })

  // 提取 dates
  const dates = data.data.chart_data.dates || []

  // 提取 series 数据
  const seriesData = data.data.chart_data.series ? data.data.chart_data.series : []

  // 更新 legend 数据
  option.legend.data = seriesData ? seriesData.map((item) => item.name) : []

  // 初始化 series 数据
  option.series = seriesData
    ? seriesData.map((item) => ({
        name: item.name,
        type: 'bar',
        data: item.data,
        backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.2)'
        },
        barWidth: 20,
        emphasis: {
          focus: 'series'
        }
      }))
    : []

  // 更新 xAxis 数据
  option.xAxis.data = dates

  // 使用 nextTick 确保 DOM 更新
  nextTick(() => {
    let chartDom = document.getElementById('category-main')
    if (chartDom) {
      let myChart = echarts.init(chartDom)
      myChart.clear() // 清空旧数据
      myChart.setOption(option)
    }
  })
}
</script>

<style lang="less" scoped>
.echarts-box {
  display: flex;
  align-items: center;
  .category-main {
    width: 100%;
    height: 280px;
    background: #fff;
  }
}
</style>
